<template>
  <div>
    <el-form
      ref="mobileForm"
      :model="mobileForm"
      :rules="mobileRules"
      class="login-form mt-10"
      auto-complete="on"
      label-position="left"
    >
      <el-form-item prop="mobile">
        <el-input
          ref="mobile"
          v-model="mobileForm.mobile"
          placeholder="请输入手机号"
          name="mobile"
          type="text"
          tabindex="1"
          autocomplete="on"
        >
          <svg-icon class="svg-container" icon-class="mobile" slot="prefix" />
        </el-input>
      </el-form-item>
      <el-form-item prop="valideCode">
        <el-input placeholder="请输入验证码" v-model="mobileForm.valideCode">
          <template slot="append">
            <span v-show="show" @click="send" class="pointer">验证码</span>
            <span v-show="!show" class="count pointer">{{count}} s</span>
          </template>
        </el-input>
      </el-form-item>
      <div class="clearfix">
        <el-link type="primary" class="float-r" @click="jumpForgetPswd">忘记密码？</el-link>
      </div>
      <el-button
        :loading="loading"
        type="primary"
        style="width:100%;margin-top:40px;"
        @click.native.prevent="getCompanys('mobileForm')"
      >登录</el-button>
    </el-form>
    <el-dialog title="选择企业登录" :modal="false" :visible.sync="visible" width="400px" append-to-body>
      <ul class="company">
        <li
          v-for="item in company"
          :key="item.account"
          @click="login(item.account)"
          class="pointer pd-10 fw-b"
        >{{item.corpName}}</li>
      </ul>
    </el-dialog>
  </div>
</template>

<script>
import { validPhone } from "@/utils/validate";
import {
  getMobileValideCode,
  getCorpAccountByMobile,
  loginByMobile
} from "api/user";
const TIME_COUNT = 60; //更改倒计时时间
export default {
  data() {
    const validateMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入手机号"));
      }
      setTimeout(() => {
        if (!validPhone(value)) {
          callback(new Error("手机号不正确"));
        } else {
          callback();
        }
      }, 300);
    };
    return {
      mobileForm: {
        mobile: "",
        valideCode: ""
      },
      mobileRules: {
        mobile: [{ validator: validateMobile, trigger: "blur" }],
        valideCode: [
          { required: true, message: "验证码不能为空", trigger: "blur" }
        ]
      },
      visible: false, // 多个企业弹出框
      company: [],
      loading: false,
      show: true, // 初始启用按钮
      count: "", // 初始化次数
      timer: null
    };
  },
  methods: {
    jumpForgetPswd() {
      this.$emit("jumpForgetPswd");
    },
    // 获取验证码
    send() {
      this.$refs.mobileForm.validateField("mobile", phoneError => {
        if (!phoneError) {
          getMobileValideCode({ mobile: this.mobileForm.mobile })
            .then(() => {
              this.countDown();
              this.$confirm("验证码已发送至登记手机号上，请查收。", {
                confirmButtonText: "确定",
                center: true
              });
            })
            .catch(err => {
              this.$message.error(err.message);
            });
        }
      });
    },
    // 倒计时
    countDown() {
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.show = false;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.show = true;
            clearInterval(this.timer); // 清除定时器
            this.timer = null;
          }
        }, 1000);
      }
    },
    getCompanys(fromName) {
      this.$refs[fromName].validate(valid => {
        if (valid) {
          if (this.loading) return;
          this.loading = true;
          getCorpAccountByMobile(this.mobileForm)
            .then(res => {
              let data = res.data;
              if (!data) return;
              if (data.length == 0) {
                this.$confirm("暂无所属企业，请联系企业添加！", "温馨提示", {
                  confirmButtonText: "确定",
                  center: true
                });
              }
              if (data.length == 1) {
                this.login(data[0].account);
              }
              if (res.data.length > 1) {
                // 多个企业需要选择登录
                this.visible = true;
                this.company = res.data;
              }
              this.loading = false;
            })
            .catch(err => {
              this.$message.error(err.msg);
            });
        }
      });
    },
    login(account) {
      let data = Object.assign({}, this.mobileForm, { account });
      this.$store.dispatch("user/mobileLogin", data).then(res => {
        this.$router.push({ path: this.redirect || "/" });
      });
    }
  }
};
</script>

<style lang='scss' scoped>
@import "styles/variables.scss";
.company {
  li {
    border-radius: 5px;
    &:hover {
      background-color: rgba($color: $themeColor, $alpha: 0.1);
    }
  }
}
</style>
